<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>着色器和GLSL语言，</title>
</head>

<body>
    <canvas id="c" width="640" height="480"></canvas>
    <script id="vertex-shader-2d" type="notjs">

  // an attribute will receive data from a buffer
  attribute vec2 a_position;
  uniform vec2 u_resolution;
  // attribute vec4 a_position;
  // all shaders have a main function
  attribute vec2 a_texCoord;
  varying vec2 v_texCoord;
  void main() {

    // gl_Position is a special variable a vertex shader
    // is responsible for setting
    // 从像素坐标转换到 0.0 到 1.0
    vec2 zeroToOne = a_position - u_resolution / 2.0;

    // 再把 0->1 转换 0->2
    vec2 zeroToTwo = zeroToOne / u_resolution * 2.0;

    // 把 0->2 转换到 -1->+1 (裁剪空间)
    // vec2 clipSpace = zeroToTwo - 1.0;

    gl_Position = vec4(zeroToTwo, 0, 1);
    gl_PointSize = 10.0;
    v_texCoord = (zeroToTwo + 1.0);
  }

</script>
    <script id="fragment-shader-2d" type="notjs">

  // fragment shaders don't have a default precision so we need
  // highp：高精度，适合需要高精度的计算。mediump：中等精度，适合一般的计算。lowp：低精度，适合颜色计算。
  precision mediump float;
  varying vec2 v_texCoord;
  uniform sampler2D u_image;
  void main() {
    // gl_FragColor is a special variable a fragment shader
    // is responsible for setting
    gl_FragColor = texture2D(u_image, v_texCoord);; // return redish-purple
  }

</script>
    <!-- <script src="https://webglfundamentals.org/webgl/resources/webgl-utils.js"></script> -->
    <script>
        /* eslint no-console:0 consistent-return:0 */
        "use strict";

        function createShader(gl, type, source) {
            var shader = gl.createShader(type);
            gl.shaderSource(shader, source);
            gl.compileShader(shader);
            var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
            if (success) {
                return shader;
            }

            console.log(gl.getShaderInfoLog(shader));
            gl.deleteShader(shader);
        }

        function createProgram(gl, vertexShader, fragmentShader) {
            var program = gl.createProgram();
            gl.attachShader(program, vertexShader);
            gl.attachShader(program, fragmentShader);
            gl.linkProgram(program);
            var success = gl.getProgramParameter(program, gl.LINK_STATUS);
            if (success) {
                return program;
            }

            console.log(gl.getProgramInfoLog(program));
            gl.deleteProgram(program);
        }

        function render(image) {
            // Get A WebGL context
            var canvas = document.querySelector("#c");
            var gl = canvas.getContext("webgl");
            if (!gl) {
                return;
            }

            // Get the strings for our GLSL shaders
            var vertexShaderSource = document.querySelector("#vertex-shader-2d").text;
            var fragmentShaderSource = document.querySelector("#fragment-shader-2d").text;

            // Set clear color to black, fully opaque
            gl.clearColor(0.0, 0.0, 0.0, 1.0);
            // Clear the color buffer with specified clear color
            gl.clear(gl.COLOR_BUFFER_BIT);

            // create GLSL shaders, upload the GLSL source, compile the shaders
            var vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
            var fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);

            // Link the two shaders into a program
            var program = createProgram(gl, vertexShader, fragmentShader);

            // Tell WebGL how to convert from clip space to pixels
            gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

            // Tell it to use our program (pair of shaders)
            gl.useProgram(program);

            // Turn on the attribute
            var resolutionUniformLocation = gl.getUniformLocation(program, "u_resolution");
            gl.uniform2f(resolutionUniformLocation, gl.canvas.width, gl.canvas.height);

            //**************************设置顶点坐标***************************
            // look up where the vertex data needs to go.
            var positionAttributeLocation = gl.getAttribLocation(program, "a_position");

           console.log(image.width, image.height);
            // Create a buffer and put three 2d clip space points in it
            var positionBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
            // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
                0, 0,
                0, image.height,
                image.width, 0,
                image.width, image.height,
            ]), gl.STATIC_DRAW);

            // Turn on the attribute‘
            gl.enableVertexAttribArray(positionAttributeLocation);

            // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
            var size = 2;          // 2 components per iteration
            var type = gl.FLOAT;   // the data is 32bit floats
            var normalize = false; // don't normalize the data
            var stride = 0;        // 0 = move forward size * sizeof(type) each iteration to get the next position
            var offset = 0;        // start at the beginning of the buffer
            gl.vertexAttribPointer(
                positionAttributeLocation, size, type, normalize, stride, offset);

            //**************************添加图像***************************

            var texture = gl.createTexture();
            gl.bindTexture(gl.TEXTURE_2D, texture);

            // Set the parameters so we can render any size image.
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

            // Upload the image into the texture.
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

            //**************************设置纹理坐标***************************
            var texcoordLocation = gl.getAttribLocation(program, "a_texCoord");
            var texcoordBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
                0.0, 0.0,
                0.0, 1.0,
                1.0, 0.0,
                1.0, 1.0,
            ]), gl.STATIC_DRAW);

            // bind the texcoord buffer.
            gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
            gl.enableVertexAttribArray(texcoordLocation);
            var size = 2;          // 2 components per iteration
            var type = gl.FLOAT;   // the data is 32bit floats
            var normalize = false; // don't normalize the data
            var stride = 0;        // 0 = move forward size * sizeof(type) each iteration to get the next position
            var offset = 0;        // start at the beginning of the buffer
            gl.vertexAttribPointer(
                texcoordLocation, size, type, normalize, stride, offset);

            // draw
            var primitiveType = gl.TRIANGLE_STRIP;
            var offset = 0;
            var count = 4;
            gl.drawArrays(gl.TRIANGLE_STRIP, offset, count);
        }

        function main() {
            var image = new Image();
            image.src = "./css/imgs/flower.png";  // 必须在同一域名下
            image.onload = function () {
                render(image);
            }
        }

        main();


    </script>
</body>

</html>